<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Repository\UpThree\ThreeOrderRepository;
use App\Repository\UpThree\MainOrderRepostition;
use App\Repository\Orders\OrdersRepository;
use Illuminate\Support\Facades\DB;
use App\Repository\AppUser\TouTiaoUserOrderRepository;

use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use App\Repository\AppUser\TouTiaoPayOrderRepository as douyinPayModel;

/**
 * @OA\Tag(
 *     name="后台菜单模块",
 *     description="菜单模块",
 * )
 */
class OrderController extends BaseController
{
  private $model;
  private $mainModel;
  private $orderModel;
  private $userOrderModel;
  private $log;
  public function __construct(ThreeOrderRepository $ThreeOrderRepository, MainOrderRepostition $MainOrderRepostition, OrdersRepository $OrdersRepository, TouTiaoUserOrderRepository $TouTiaoUserOrderRepository)
  {
    $this->model = $ThreeOrderRepository;
    $this->mainModel = $MainOrderRepostition;
    $this->orderModel = $OrdersRepository;
    $this->userOrderModel = $TouTiaoUserOrderRepository;
    $this->log = new Logger('ExternalPush');
    $this->log->pushHandler(
      (new RotatingFileHandler(storage_path('/logs/ExternalPush.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
    );
  }
  //下单接口 目前不使用 (直接提交到了 第三方)
  public function orderSubmit(Request $request)
  {
    $param = $request->all();
    $param['source'] = 3;
    return $this->model->orderSubmit($param);
  }
  // 下单接口  H5 页面过来的订单
  public function submit(Request $request)
  {

    $param = $request->all();
    // source 类型 1 => '抖音',
    // 2 => '导入',
    // 3 => 'H5',
    // 4 => '百度',
    // 5 => 'Api',
    $param['source'] = 3;
    if (!empty($param['area']) && strrpos($param['area'], ' ') !== false) {
      $arr = explode(' ', $param['area']);
      $param['province'] = $arr[0];
      $param['city'] = $arr[1];
      $param['area'] = $arr[2];
    }
    if (!empty($param['numberCity'])) {
      $arrs = explode(' ', $param['numberCity']);
      $param['numberProvince'] = $arrs[0];
      $param['numberCity'] = $arrs[1];
    }
    if (!empty($param['sell_id'])) {
      $param['sell_name'] = $param['sell_id'];
    }
    // 查询订单 秒杀活动处理
    // $whereGoods = [
    //   'is_top' => 1,
    // ];
    // if (!empty($param['goods_id'])) {
    //   $whereGoods['id'] = $param['goods_id'];
    // }
    // if (!empty($param['goods_code']) && !empty($param['shop_id'])) {
    //   $whereGoods['goods_code'] = $param['goods_code'];
    //   $whereGoods['shop_id'] = $param['shop_id'];
    // }
    // $isTrue = DB::Table('goods')->where($whereGoods)->first();
    // if (!$isTrue) {
    //   return $this->returnMsg(109, '联系主播开启活动');
    // }
    // return $this->mainModel->orderSubmit($param);
    $datas =  $this->mainModel->orderSubmit($param);
    if (!empty($datas['code']) && $datas['code'] == 200) {
      return $this->returnMsg(200, '重要提示：已领取，切记找主播：①-确认是否成功，避免失败延误；②-备注加急审核发货，赠送体验话费。', $datas['data']);
      // return $this->returnMsg(200, '重要提示：已领取，切记找主播：①-确认是否成功，避免失败延误；②-备注加急审核发货。', $datas['data']);
      // return $this->returnMsg(200, '重要提示：已领取，此项服务为粉丝团成员专享，请点关注+粉丝团，给主播回复手机号后4位备注，老号转套餐回复：8888老号转套餐已领取；办新号回复：8888办新号已领取。', $datas['data']);
      // return $this->returnMsg(200, '重要提示：已领取，请给主播回复手机号后4位备注，示例：8888老号转套餐已领取', $datas['data']);
    }
    return $datas;
  }
  //通过接口过来的订单 通过api过来的订单
  public function purchaseOrder(Request $request)
  {
    $param = $request->all();
    // source 类型 1 => '抖音',
    // 2 => '导入',
    // 3 => 'H5',
    // 4 => '百度',
    // 5 => 'Api',
    $this->log->info('api过来的参数:' . json_encode($param));
    $param['source'] = 5;
    if (empty($param['goods_code']) && empty($param['shop_id'])) {
      return $this->returnMsg(1, '请传递商品编码和店铺参数');
    }
    if (!empty($param['goods_id'])) {
      $param['goods_id']  = 0;
    }
    if (!empty($param['area']) && strrpos($param['area'], ' ') !== false) {
      $arr = explode(' ', $param['area']);
      if (count($arr) < 3) {
        return $this->returnMsg(101, '地址参数有问题,请传递正确的参数');
      }
      $param['province'] = $arr[0];
      $param['city'] = $arr[1];

      $param['area'] = $arr[2];
    }
    if (!empty($param['numberCity'])) {
      $arrs = explode(' ', $param['numberCity']);
      $param['numberProvince'] = $arrs[0];
      $param['numberCity'] = $arrs[1];
    }
    return $this->mainModel->orderSubmit($param);
  }
  // 小程序支付的单
  public function purchasePayAppOrder(Request $request)
  {
  }
  // 小程序订单
  public function purchaseAppOrder(Request $request)
  {
    $param = $request->all();
    // source 类型 1 => '抖音',
    // 2 => '导入',
    // 3 => 'H5',
    // 4 => '百度',
    // 5 => 'Api',
    $this->log->info('小程序api过来的参数:' . json_encode($param));
    $param['source'] = 8;
    $url = $_SERVER['HTTP_HOST'];
    // var_dump($url);
    $path = 'http://';
    if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ||  $_SERVER['SERVER_PORT'] == '443') {
      $path = 'https://';
    }
    if (empty($param['goods_code']) && empty($param['shop_id'])) {
      return $this->returnMsg(1, '请传递商品编码和店铺参数');
    }
    if (!empty($param['goods_id'])) {
      $param['goods_id']  = 0;
    }
    if (!empty($param['area']) && strrpos($param['area'], ' ') !== false) {
      $arr = explode(' ', $param['area']);
      if (count($arr) < 3) {
        return $this->returnMsg(101, '地址参数有问题,请传递正确的参数');
      }
      $param['province'] = $arr[0];
      $param['city'] = $arr[1];

      $param['area'] = $arr[2];
    }
    if (!empty($param['numberCity'])) {
      $arrs = explode(' ', $param['numberCity']);
      $param['numberProvince'] = $arrs[0];
      $param['numberCity'] = $arrs[1];
    }
    $user_id = 0;
    if (!empty($param['user_id'])) {
      $user_id = $param['user_id'];
    }
    if (!empty($user_id)) {
      $douYinUser = DB::table('toutiao_user')->where(['id' => $user_id])->first();
      if (!$douYinUser) {
        return $this->returnMsg(100, '未查询到用户信息');
      }
    }
    if (empty($douYinUser)) {
      return $this->returnMsg(100, '请返回首页刷新页面并授权该网站允许读取信息');
    }
    // 查询订单 秒杀活动处理
    $whereGoods = [
      'is_top' => 1,
    ];
    if (!empty($param['goods_id'])) {
      $whereGoods['id'] = $param['goods_id'];
    }
    if (!empty($param['goods_code']) && !empty($param['shop_id'])) {
      $whereGoods['goods_code'] = $param['goods_code'];
      $whereGoods['shop_id'] = $param['shop_id'];
    }
    // var_dump($whereGoods, 1111111111);
    $isTrue = DB::Table('goods')->where($whereGoods)->first();
    // var_dump($isTrue, 333333333);
    if (!$isTrue) {
      return $this->returnMsg(109, '联系主播开启活动');
    }
    $datas =  $this->mainModel->orderSubmit($param);
    // 记录中间表
    if (!empty($datas['code']) && $datas['code'] == 200 && !empty($datas['data']['order_num'])) {
      $insert = [
        'user_id' => $user_id,
        'orderno' => $datas['data']['order_num'],
        'money' => !empty($datas['data']['money']) ? $datas['data']['money'] : 0,
        'shop_id' => $douYinUser->shop_id,
        'status' => 1,
        'main_pic' => $path . $url . $datas['data']['goods_url'],
        'goods_id' => $param['goods_id'],
        'goods_name' => $datas['data']['goods_name']
      ];
      if (empty($insert['money'])) {
        $insert['status'] = 4; // 无需付款
        $insert['remark'] = '无需付款';
      }
      $this->userOrderModel->addOrEdit($insert);
    }
    // 订单预付单
    if (!empty($insert['money'])) {
      // 抖音的预付单
      $douyinConfig = DB::table('app_douyin_config')->where(['shop_id' => $douYinUser->shop_id])->first();
      // var_dump($douyinConfig, 5555555555);
      if (empty($douyinConfig) || empty($douyinConfig->app_key)) {
        return $this->returnMsg(100, '未查询到订单,请重新下单');
      }
      $model = new douyinPayModel();
      $payData = [
        'app_id' => $douyinConfig->app_key,
        'app_secret' => $douyinConfig->app_secret,
        'out_order_no' => $insert['orderno'],
        'total_amount' => $insert['money'],
        'subject' => $datas['data']['goods_name'],
        'body' => $datas['data']['goods_point'],
        'access_token_json' => $douyinConfig->parame,
        'open_id' => $douYinUser->openid,
        'path' => 'pages/goodsDetail/goodsDetail?id=' . $param['goods_id'],
        'goods_id' => $param['goods_id'],
        'img' => $path . $url . $datas['data']['goods_url'],
        'shop_id' => $douYinUser->shop_id,
      ];
      // $model->pushOrder($payData);
      // 调起支付
      $returns = $model->preOrder($payData);

      if (isset($returns['err_no']) && $returns['err_no'] == 0) {
        $datas['data']['order_id'] = $returns['data']['order_id'];
        $datas['data']['order_token'] = $returns['data']['order_token'];
      }
    }

    return $datas;
  }
  // 抖音小程序 订单查询
  public function getAppOrderDetail(Request $request)
  {
    $param = $request->all();
    if (empty($param['user'])) {
      return $this->returnMsg(100, '请登录');
    }
    $where = [
      'where' => [
        'toutiao_user_order.user_id' => $param['user'],
        // 'toutiao_user_order.shop_id' => $param['shopId'],
      ],
      'join' => [
        [
          'table' => 'orders',
          'left' => 'ordersno',
          'right' => 'toutiao_user_order.orderno'
        ]
      ],
      'order' => [
        'orderby' => 'toutiao_user_order.id',
        'orderdir' => 'DESC'
      ],
      'select' => ['toutiao_user_order.*', 'toutiao_user_order.goods_name as toutiao_goods_name', 'orders.goods_name', 'orders.status as order_status'],
    ];
    // return $this->returnMsg(200, '查询成功');
    $datas =  $this->userOrderModel->sel($where);
    $returns = [
      'all' => [],
      'daichuli' => [],
      'daishouhuo' => [],
      'yiwancheng' => [],
      'yiquxiao' => [],
    ];
    if (!empty($datas['data'])) {
      foreach ($datas['data']  as $key => &$v) {
        // if(!empty()){
        //   // $v['main_pic'] = $path . $url . $v['main_pic'];
        // }
        $v['status_desc'] = $this->userOrderModel->getStatusDesc($v['status']);

        $status = $v['order_status'];
        if (!empty($v['money'])) {
          $v['money'] = $v['money'] / 100;
        }
        // $v['is_quxiao'] = 1; // 未付款
        // [
        //   'is_quxiao' => 1, // 未付款
        //   'is_quxiao' => 2, // 已付款
        //   'is_quxiao' => 3, // 已退款已取消
        //   'is_quxiao' => 4, // 无需付款
        //   'is_quxiao' => 5, // 已取消
        // ];
        // 待处理  status = 1  || status = 4 && orders_status = 1
        // 待收货 status = 2 || status = 4 && orders_status > 10 && orders_status <= 20
        // 已完成 status = 2 || status = 4 && orders_status > 20 && orders_status <= 40 
        // 已取消 status = 3 || status = 5 || orders_status > 40 
        $v['is_quxiao'] = 1; // 根据他显示 已取消或退款取消 
        $v['desc'] = '已取消';
        $v['is_pay'] = '超时未支付';
        if ($v['status'] == 2 || $v['status'] == 4) {
          if ($status >= 0 && $status <= 10) {
            $v['is_quxiao'] = 5;  // 待处理
            if ($v['status'] == 2) {
              $v['desc'] = '已支付';
              $v['is_pay'] = '退款';
            } else {
              $v['desc'] = '商家待处理';
              $v['is_pay'] = '取消订单';
            }
            $returns['daichuli'][] = $v;
          } else if ($status > 10 && $status <= 20) {
            $v['is_quxiao'] = 2;  // 待收货
            $v['desc'] = '待收货';
            $returns['daishouhuo'][] = $v;
          } else if ($status > 20 && $status <= 40) {
            $v['is_quxiao'] = 3;  // 已完成
            $v['desc'] = '已完成';
            $returns['yiwancheng'][] = $v;
          } else if ($status > 40) {
            $v['is_quxiao'] = 4;  // 商家审核失败
            if ($v['status'] == 4) {
              $v['desc'] = '商家审核失败';
            } else {
              $v['desc'] = '商家审核失败并退款';
            }
            $returns['yiquxiao'][] = $v;
          }
        } elseif ($v['status'] == 3) {
          $v['is_quxiao'] = 4;  // 商家审核失败
          $v['desc'] = '已取消退款中';
          $returns['yiquxiao'][] = $v;
        } elseif ($v['status'] == 6) {
          $v['is_quxiao'] = 4;  // 商家审核失败
          $v['desc'] = '已取消已退款';
          $returns['yiquxiao'][] = $v;
        } elseif ($v['status'] == 5) {
          $v['is_quxiao'] = 4;  // 商家审核失败
          $v['desc'] = '已取消不退款';
          $returns['yiquxiao'][] = $v;
        } else if ($v['status'] == 7) {
          $v['is_quxiao'] = 4;  // 商家审核失败
          $v['desc'] = '取消支付';
          $returns['yiquxiao'][] = $v;
        } else if ($v['status'] == 8) {
          $v['is_quxiao'] = 4;  // 商家审核失败
          $v['desc'] = '商家审核未过';
          $returns['yiquxiao'][] = $v;
        } else {
          $v['is_quxiao'] = 1;  // 商家审核失败
          $returns['yiquxiao'][] = $v;
          // $v['desc'] = '已取消';
          // $v['is_pay'] = '超时未支付';
        }

        $returns['all'][] = $v;
      }
    }
    return $this->returnMsg(200, '查询成功', $returns);
  }
  // 抖音小程序 修改订单状态
  public function editOrdersStatus(Request $request)
  {
    $params = $request->all();
    if (empty($params['id'])) {
      return $this->returnMsg(100, '请传递需要参数');
    }
    if (empty($params['user'])) {
      return $this->returnMsg(102, '请登录');
    }
    $update = [
      'status' => 5
    ];
    $res = $this->userOrderModel->edit(['id' => $params['id']], $update);
    if ($res) {
      return $this->returnMsg(200, '取消成功', $res);
    }
  }
  public function editOrdersIsPay(Request $request)
  {
    $params = $request->all();
    if (empty($params['pay'])) {
      return $this->returnMsg(100, '请传递需要参数');
    }
    if (empty($params['orderno'])) {
      return $this->returnMsg(102, '请登录');
    }
    $update = [
      'status' => $params['pay']
    ];
    $res = $this->userOrderModel->edit(['orderno' => $params['orderno']], $update);
    if ($res) {
      return $this->returnMsg(200, '取消成功', $res);
    }
  }
  // 物流信息查询
  public function getOrderDetail(Request $request)
  {
    $phone = $request->get('phone');
    $password = $request->get('password');
    $shop_id = $request->get('shop_id');
    // if ($password != '123456') {
    //   return $this->returnMsg(100, '密码错误');
    // }
    if (empty($password)) {
      return $this->returnMsg(100, '密码错误');
    }
    if (strlen($password) != 6) {
      return $this->returnMsg(101, '密码长度不够');
    }
    if (empty($shop_id)) {
      return $this->returnMsg(101, '请联系主播或商家');
    }
    $where = [
      ['orders_user.pay_phone', '=', $phone],
      ['orders_user.pay_identity', 'like', '%' . $password],
      ['orders.sup_id', '!=', 8],
      ['orders.nums', '=', 1],
      ['orders.shop_id', '=', $shop_id]
    ];
    $data = $this->orderModel->getOne($where, ['orders.id', 'orders.status_desc', 'orders.express_number', 'orders.express_company', 'orders.iccid', 'orders.goods_name', 'orders.goods_id']);
    // var_dump($data);
    if (!empty($data['goods_id'])) {
      $goodsArr = DB::Table('goods')->where(['id' => $data['goods_id']])->select(['id', 'tishi', 'goods_point'])->first();
      if ($goodsArr && $goodsArr->goods_point != '') {
        $data['tishi'] = $goodsArr->goods_point;
      }
    }
    if (empty($data)) {
      return $this->returnMsg(100, '未查询到订单');
    }
    return $this->returnMsg(200, '查询成功', $data);
  }
  public function getApiOrderDetail(Request $request)
  {
    $order = $request->get('orderno');
    $distOrder = $request->get('dist_orderno');
    // if ($password != '123456') {
    //   return $this->returnMsg(100, '密码错误');
    // }
    if (empty($order) && empty($distOrder)) {
      return $this->returnMsg(100, '请传递单号');
    }
    $where = [];
    if (!empty($order)) {
      // return $this->returnMsg(100, '密码错误');
      $where = [
        'ordersno' => $order
      ];
    }
    if (!empty($distOrder)) {
      // return $this->returnMsg(100, '密码错误');
      $where = [
        'orders_user.dist_orderno' => $distOrder
      ];
    }
    $data = $this->orderModel->getOne($where, ['orders.id', 'orders.ordersno', 'orders.status', 'orders.status_desc', 'orders.express_number', 'orders.express_company', 'orders.iccid', 'orders.first_status', 'orders.three_msg as msg']);
    // var_dump($data);
    if (empty($data)) {
      return $this->returnMsg(100, '未查询到订单');
    }
    return $this->returnMsg(200, '查询成功', $data);
  }
  public function ganPurchaseOrder(Request $request)
  {
    // $param = $request->all();
    $getData = file_get_contents('php://input');
    // var_dump($getData, 111111111);
    // var_dump(json_decode($getData, true), 3333333333333);
    if (!empty($getData)) {
      $param = json_decode($getData, true);
    }
    if (empty($param)) {
      // $param = file_get_contents('php://input');
      $param = $request->all();
    }
    // var_dump($param, 555555555555555);
    // source 类型 1 => '抖音',
    // 2 => '导入',
    // 3 => 'H5',
    // 4 => '百度',
    // 5 => 'Api',
    $this->log->info('感叹号api过来的参数:' . json_encode($param));
    $param['source'] = 7;
    // if (empty($param['goods_code']) && empty($param['shop_id'])) {
    //   return $this->returnMsg(1, '请传递商品编码和店铺参数');
    // }
    // if (!empty($param['goods_id'])) {
    //   $param['goods_id']  = 0;
    // }
    // if (empty($param['good_id'])) {
    //   return $this->returnMsg(100, '请传递下单的商品');
    // }
    if (!empty($param['area']) && strrpos($param['area'], ' ') !== false) {
      $arr = explode(' ', $param['area']);
      if (count($arr) < 3) {
        return $this->returnMsg(101, '地址参数有问题,请传递正确的参数');
      }
      $param['province'] = $arr[0];
      $param['city'] = $arr[1];

      $param['area'] = $arr[2];
    }
    if (!empty($param['order_num'])) {
      $param['dist_orderno'] = $param['order_num'];
    }
    if (!empty($param['good_id'])) {
      $param['goods_id'] = $param['good_id'];
    }
    if (!empty($param['card_num'])) {
      $param['identity'] = $param['card_num'];
      unset($param['card_num']);
    }
    if (!empty($param['user_name'])) {
      $param['name'] = $param['user_name'];
    }
    if (!empty($param['user_phone'])) {
      $param['contact'] = $param['user_phone'];
    }
    if (!empty($param['numberCity'])) {
      $arrs = explode(' ', $param['numberCity']);
      $param['numberProvince'] = $arrs[0];
      $param['numberCity'] = $arrs[1];
    }
    return $this->mainModel->orderSubmit($param);
  }
  public function baiduPurchaseOrder(Request $request)
  {
    $param = $request->all();
    // source 类型 1 => '抖音',
    // 2 => '导入',
    // 3 => 'H5',
    // 4 => '百度',
    // 5 => 'Api',
    $this->log->info('api过来的参数:' . json_encode($param));
    $param['source'] = 4;
    // if (empty($param['goods_code']) && empty($param['shop_id'])) {
    //   return $this->returnMsg(1, '请传递商品编码和店铺参数');
    // }
    // if (!empty($param['goods_id'])) {
    //   $param['goods_id']  = 0;
    // }
    if (empty($param['good_id'])) {
      return $this->returnMsg(100, '请传递下单的商品');
    }
    if (!empty($param['area']) && strrpos($param['area'], ' ') !== false) {
      $arr = explode(' ', $param['area']);
      if (count($arr) < 3) {
        return $this->returnMsg(101, '地址参数有问题,请传递正确的参数');
      }
      $param['province'] = $arr[0];
      $param['city'] = $arr[1];

      $param['area'] = $arr[2];
    }
    if (!empty($param['order_num'])) {
      $param['dist_orderno'] = $param['order_num'];
    }
    if (!empty($param['good_id'])) {
      $param['goods_id'] = $param['good_id'];
    }
    if (!empty($param['real_identityid'])) {
      $param['identity'] = $param['real_identityid'];
      unset($param['real_identityid']);
    }
    if (!empty($param['real_name'])) {
      $param['name'] = $param['real_name'];
    }
    if (!empty($param['phone'])) {
      $param['contact'] = $param['phone'];
    }
    if (!empty($param['sheng'])) {
      $param['province'] = $param['sheng'];
    }
    if (!empty($param['shi'])) {
      $param['city'] = $param['shi'];
    }
    if (!empty($param['qu'])) {
      $param['area'] = $param['qu'];
    }
    if (!empty($param['adress'])) {
      $param['address'] = $param['adress'];
    }
    if (!empty($param['numberCity'])) {
      $arrs = explode(' ', $param['numberCity']);
      $param['numberProvince'] = $arrs[0];
      $param['numberCity'] = $arrs[1];
    }
    $res = $this->mainModel->orderSubmit($param);
    return json_encode($res, JSON_UNESCAPED_UNICODE);
  }
}
